<template>
  <!-- <Index_top></Index_top> -->
  <div class="box" v-transition>
    <!-- 可使用 router 实现 -->

    <!-- 已注册 -->
    <div v-if="activate==4">
      <Title :place="place" :icon="icon" @handleTitleClick="handleTitleClick" :title="title_home"></Title>
      <div>
        <IndexTop :amountArr="amountArr"></IndexTop>
        <Amount @junmpRecharge="junmpRecharge" @jumpHelp="jumpHelp"></Amount>
      </div>
      <div ref="BILL">
        <Bill
          :billHeight="billHeight"
          :list="list"
          @next="next"
          @pre="pre"
          @getPageNum="getPageNum"
          @getAllBill="getAllBill"
          @jumpDetail="jumpDetail"
        ></Bill>
      </div>
    </div>

    <!-- 未注册 -->
    <div v-else-if="  activate==1  || activate==2 ">
      <Activate @ActivateHandleTitleClick="ActivateHandleTitleClick" @openPayment="openPayment"></Activate>
    </div>

    <!-- 去签约 -->
    <div v-else-if="activate==3" v-load="flg">
      <SecretPay
        @ActivateHandleTitleClick="ActivateHandleTitleClick"
        @openSecretPay="openSecretPay"
      ></SecretPay>
    </div>

   
      

    <PayKeyBoard ref="passBox1" v-if="showKB1" @cancel="cancel1" @done="done1" :text="text1"></PayKeyBoard>

    <PayKeyBoard v-if="showKB2" @cancel="cancel2" @done="done2" :text="text2"></PayKeyBoard>

    <PayKeyBoard
      v-if="showKB3"
      @forgetPass="forgetPass"
      @cancel="cancel3"
      @done="done3"
      :text="text3"
      :forgetTxt="forgetTxt"
    ></PayKeyBoard>
  </div>
</template>

<script>
import common from "../common/index";
import Utility from "../common/Utility"
import IndexTop from "../layout/IndexTop";
import Title from "../layout/Title";
import Amount from "../layout/Amount";
import Bill from "../layout/Bill";
import Activate from "../layout/Activate";
import SecretPay from "../layout/SecretPayment";
import PayKeyBoard from "../layout/PayKeyBoard";
import {
  getAvailableBalance,
  getIndexListInfo,
  initPassword,
  confirmContract,
  getInfoByIdUrl
} from "../Ajax/index";

import { Indicator } from "mint-ui";
export default {
  name: "Home",
  components: {
    Title,
    IndexTop,
    Amount,
    Bill,
    Activate,
    SecretPay,
    PayKeyBoard
  },
  directives: {
    load: (el, binding) => {
      if (binding.value == 1) {
        const div = document.createElement("div");
        (div.innerText = "Loading。。。"),
          div.setAttribute("id", "load"),
          (div.style.position = "fixed");
        div.style.zIndex = "200";
        div.style.left = "0";
        div.style.top = "0";
        div.style.width = "100%";
        div.style.height = "100%";
        div.style.display = "flex";
        div.style.justifyContent = "center";
        div.style.alignItems = "center";
        div.style.color = "white";
        div.style.background = "rgba(0,0,0,.8)";
        document.body.append(div);
      } else if (binding.value == 2) {
        try {
          const div = document.getElementById("load");

          div && document.body.removeChild(div);
        } catch (error) {}
      }
    }
  },
  data() {
    return {
      title_home: "ZegoPay",
      activate: "",
      slotplace: "",
      icon: "shezhi",
      place: "right",

      billHeight:
        // 40 164 40  30(顶部预留距离)
        (document.documentElement.clientHeight || document.body.clientHeight) -
        244,
      showKB1: false,
      showKB2: false,
      text1: this.Lang[this.$store.state.lang].setPass,
      text2: this.Lang[this.$store.state.lang].confirmPass,

      password: {
        pass1: "",
        pass2: ""
      },
      offset: "1", //页数必须大于1
      page: "", //每页 的数量
      amountArr: {
        ffixedBalance: "******",
        favailableBalance: "******",
        ffreezeBal: "******"
      },
      list: [
        //   {
        //   entName:"6654554565222222229999999999999",
        //   tradeTime:"2020-06-03  19:56:36",
        //   payAmount:100000000
        // },{
        //    entName:"66545545652222229999999999999999",
        //   tradeTime:"2020-06-03  19:56:36",
        //   payAmount:100000000,
        //   imageUrl:" http://devtest.zegopay.com:18081/upload/image/3e/26/3e268ed5c721081ea48b17c3cf93dbf7.jpeg"
        // },{
        //     entName:"6654554565222222266",
        //   tradeTime:"2020-06-03  19:56:36",
        //   payAmount:100000000
        // },
      ],

      isOK: true,
      showKB3: false,
      text3: this.Lang[this.$store.state.lang].openZego_text,
      forgetTxt: this.Lang[this.$store.state.lang].forgetTxt,
      flg: 0
    };
  },
  methods: {
    forgetPass() {
      this.flg = 1;
      // alert(0)
      //   setTimeout(() => {
      //   this.showKB3 = false;
      // }, 200);
      // this.cancel3()
      // this.$router.push({
      //   path:"/changePassword"
      // })

      setTimeout(() => {
        this.showKB3 = false;
        this.flg = 2;

        setTimeout(() => {
          this.$router.push({
            path: "/changePassword"
          });
        }, 10);
      }, 200);
    },
    getUserInfo() {
      this.activate = this.$store.state.userInfo.activate;

      let isRecharge= this.activate == "5"? "true" :"false"

      let params = common.formdata({
        fuid: this.$store.state.userInfo.fuid,
        timeStamp: new Date().getTime()
        // obj: this.$store.state.userInfo.fuid
      });

      new Promise((resolve,reject)=>{

        

          getInfoByIdUrl(params)
        .then(res => {
          this.$store.state.userInfo.fimageUrl =
            res.data.datas.userInfo.fimageUrl;
          this.$store.state.userInfo.fmobile = res.data.datas.userInfo.fmobile;
          this.$store.state.userInfo.funame = res.data.datas.userInfo.funame;

          if(isRecharge == "true"){
            resolve()
          }
        })
        .catch(err => {
          common.toast({
            message: this.Lang[this.$store.state.lang][err] || err,
            time: 2000
          });
        });


      }).then(()=>{
        this.$router.replace("/Recharge")
      })

     

      // 保存用户信息 到vuex 里   获取地理定位 语言 fuid
      // let lan = this.$store.state.lang;
      // console.log(this.$store.state);
      // alert(lan)
      // this.text1 = this.Lang[lan].setPass;
      // this.text2 = this.Lang[lan].confirmPass;

      // this.$store.state.fuid = "100001000";
    },
    junmpRecharge() {
      // alert(666);
      this.$router.push({
        path: "/Recharge"
      });
    },
    jumpHelp() {
      window.location.href = "http://video.zegobird.com:8081/zegopayHelp2/";
    },
    next() {
      this.offset = parseInt(this.offset) + 1;
      this.initList();
    },
    pre() {
      // this.list = [];

      let offset = this.offset <= "1" ? "1" : this.offset - 1;

      this.offset = parseInt(offset);
      this.initList();
    },
    initList() {
      //  每次刷新列表  都 更新 余额

      if (this.isOK) {
        this.isOK = false;

        new Promise((resolve, reject) => {
          setTimeout(() => {
            let params = common.formdata({
              fuid: this.$store.state.userInfo.fuid,
              timeStamp: new Date().getTime(),
              // obj: this.$store.state.userInfo.fuid,
              offset: this.offset,
              limit: this.page

              // month: ""
            });

            // console.log(params.pageInfo)
            getIndexListInfo(params)
              .then(res => {
                resolve();
                if (res.data.datas.userOrderList.data.length == 0) {
                  //  alert(666)

                  this.offset = parseInt(this.offset - 1);
                  //  alert("无更多数据了")
                  common.toast({
                    message: this.Lang[this.$store.state.lang].bill_nomore,
                    time: 2000
                  });
                } else {
                  this.list = res.data.datas.userOrderList.data;
                }
                this.isOK = true;
              })
              .catch(err => {
                console.log(err);
                common.toast({
                  message: this.Lang[this.$store.state.lang][err] || err,
                  time: 2000
                });
              });
          }, 10);
        }).then(() => {
          // 获取 账户 余额
          setTimeout(() => {
            let params = common.formdata({
              userId: this.$store.state.userInfo.fuid,
              timeStamp: new Date().getTime()
              // obj: this.$store.state.userInfo.fuid
            });
            // console.log("params", params);
            getAvailableBalance(params)
              .then(res => {
                this.amountArr = {
                  ffixedBalance: res.data.datas.userCredit.ffixedBalance,
                  favailableBalance:
                    Number(res.data.datas.userCredit.favailableBalance) -
                    Number(res.data.datas.userCredit.ffreezeBal),
                  //  res.data.datas.userCredit.favailableBalance-res.data.datas.userCredit.ffreezeBal,

                  ffreezeBal: res.data.datas.userCredit.ffreezeBal
                };
                // console.log(res.data.datas.userCredit.favailableBalance)
              })
              .catch(err => {
                // console.log(err)
                common.toast({
                  // message: this.Lang[this.$store.state.lang]["netWork"]  || err,
                  message: err,
                  time: 2000
                });
              });
          }, 100);
          // 获取 账户 余额
        });

        // alert(1)
      }
    },

    getPageNum(num) {
      this.page = parseInt(num);
      this.initList();
    },
    handleTitleClick() {
      this.$router.push({
        path: "/personCenter"
      });
    },
    getAllBill() {
      // alert("more");
      this.$router.push({
        path: "./moreBill"
      });
    },
    ActivateHandleTitleClick() {
      alert("退出webview");
    },
    openPayment() {
      // 开通支付
      // alert("开通支付")
      this.showKB1 = true;
    },
    cancel1() {
      // this.showKB=false
      setTimeout(() => {
        this.showKB1 = false;
      }, 200);
    },
    cancel2() {
      setTimeout(() => {
        this.showKB2 = false;
      }, 200);
    },
    done1(val) {
      this.$refs["passBox1"].box.width = "0px";
      this.$refs["passBox1"].box.opacity = "0";
      this.$refs["passBox1"].box.transition = "all 0.3s";
      this.$refs["passBox1"].webkitTransition = "all 0.3s";
      this.password.pass1 = val;

      setTimeout(() => {
        this.showKB1 = false;
        // this.showKB2 = true
        setTimeout(() => {
          this.showKB2 = true;
        }, 200);
      }, 500);
    },
    done2(val) {
        var _this=this
      this.password.pass2 = val;
      console.log(this.password);
      setTimeout(() => {
        Indicator.open();
        this.showKB2 = false;

        setTimeout(() => {
           // 对明文密码加密
                     let en=Utility.pass_PublicKey
                          let jse = new _this.$jsEncrypt()
                        jse.setPublicKey(en)
                        // var encrypted = jse.encrypt(params)
                    let newPass=jse.encrypt(this.password.pass1)
                    let confirmPass=jse.encrypt(this.password.pass2)
                    
              //对明文密码加密
 

          let params = common.formdata({
            fuid: this.$store.state.userInfo.fuid,
            timeStamp: new Date().getTime(),
            // obj: this.$store.state.userInfo.fuid,
            newPass: newPass,
            confirmPass: confirmPass
          });

          initPassword(params)
            .then(res => {
              Indicator.close();
              this.$store.state.userInfo.activate = 4;
              this.activate = 4;
            })
            .catch(err => {
              Indicator.close();
              common.toast({
                message: this.Lang[this.$store.state.lang][err] || err,
                time: 2000
              });
            });
        }, 200);
      }, 200);
    },
    openSecretPay() {
      // 开通免密
      // alert(999)
      this.showKB3 = true;
    },
    cancel3() {
      setTimeout(() => {
        this.showKB3 = false;
      }, 200);
    },
    done3(val) {
      // alert(val)

      var str = JSON.stringify({
        fuid: this.$store.state.userInfo.fuid,
        password: val,
        fmchId: this.$store.state.userInfo.fmchId,
        contrId: this.$store.state.userInfo.contrId,
        mchClientIp: this.$store.state.userInfo.mchClientIp
      });

      // var jse = new this.jsEncrypt();
      // jse.setPublicKey(encrypt_PublicKey);
      var realParam = this.RSA.encrypt(str);

      let params = common.formdata({
        fuid: this.$store.state.userInfo.fuid,
        timeStamp: new Date().getTime(),
        // obj: this.$store.state.userInfo.fuid,
        params: encodeURIComponent(realParam)
      });

      confirmContract(params)
        .then(res => {
          this.$store.state.userInfo.activate = 4;
          this.$router.push({
            path: "./openOK"
          });
          //  window.zegopay.returnMain();
        })
        .catch(err => {
          this.showKB3 = false;
          common.toast({
            message: this.Lang[this.$store.state.lang][err] || err,
            time: 2000
          });
        });
    },
    jumpDetail(data) {
      console.log("detailInfo", JSON.parse(data));
      this.$store.state.detailInfo = data;
      this.$router.push({
        path: "./detail"
      });
    }
  },
  created(){
      // console.log("status", this.$store.state.userInfo.fuid)
      // new Promise(async (resolve,reject)=>{
      //   await  this.getUserInfo()
      //   resolve()

      // }).then(()=>{
      //   // alert("666")
      //   this.$router.replace("/Recharge")
      // })
      


  },

  mounted() {
    common.loading();
    setTimeout(() => {
      common.hide();
      this.getUserInfo();
    }, 10);

    setTimeout(() => {
      console.log("vuex", this.$store.state);
    }, 2000);
  }
};
</script>

<style scoped>
.box {
  width: 100%;
  /* background: transparent; */
}
</style>